<?php
class PERSONS{
    //general variables
	var $dbErrorMsg = "Failed set/get data from database (Class persons): ";

    /** Function for getting the user
     * @param  $personId
     * @return void
     */
    function getPerson($personId=0){    	
        if($personId == 0){
        $sql="describe `".tblPrefix."persons`";
    		$tmpres=MAIN::returnArray($sql);
    		$res=array();
    		foreach($tmpres as $r){
    			if($r['Field']=='id'){
    				$res[0][$r['Field']]=0;
    			}else{
    				$res[0][$r['Field']]='';
    			}    			
    		}
        }else{
	    	if($personId == -1){$personId=MAIN::decode($_SESSION[svar]);}
			$sql="select `".tblPrefix."persons`.*,`".tblPrefix."users`.*,`".tblPrefix."persons`.`id`,`".tblPrefix."persons`.`association_id`
				from `".tblPrefix."persons`	
				LEFT JOIN `".tblPrefix."users` ON `".tblPrefix."persons`.`user_id`=`".tblPrefix."users`.`id`			 			 
				 where `".tblPrefix."persons`.`id`=".$personId;
			$res=MAIN::returnArray($sql);
        }
        return @$res[0];
    }	
	/** Funtion return User full name as string
     * params : userId
     * return : string
     */
	function getPersonFullName($personId){
		$sql="select * from `".tblPrefix."persons` where `id`=".$personId;
		$res = MAIN::returnArray($sql);
		return $res[0]['firstname']." ".$res[0]['lastname'];
	}
	/** Function add/update user
	 * params : posted data in DATA array, user ID, boolean if create user phpBB
	 * return: userId 
	 */
    function setPerson($id,$DATA){
    	$userId=mysql_real_escape_string($DATA['txt_user_id']);
    	$firstName=mysql_real_escape_string($DATA['txt_person_firstname']);
    	$lastName=mysql_real_escape_string($DATA['txt_person_lastname']);
		$pers=mysql_real_escape_string($DATA['txt_person_pers']);
    	$address=mysql_real_escape_string($DATA['txt_person_address']);
    	$zip=mysql_real_escape_string($DATA['txt_person_zip']);
    	$city=mysql_real_escape_string($DATA['txt_person_city']);
    	$tel=mysql_real_escape_string($DATA['txt_person_tel']);
		$email=mysql_real_escape_string(@$DATA['txt_person_email']);
		$associationId=mysql_real_escape_string(@$DATA['ddl_association']);
    	$sql="select `".tblPrefix."persons`.`id` from `".tblPrefix."persons` where `".tblPrefix."persons`.`id`=".$id;
		$res=MAIN::returnArray($sql);    		
        if(count($res)>0){
        	//edit
        	$sql = "update `".tblPrefix."persons` set 
				`user_id`=".$userId.",`firstname`='".$firstName."',`lastname`='".$lastName."',`address`='".$address."',`zip`='".$zip."',
				`city`='".$city."',`tel`='".$tel."',`emailp`='".$email."',`association_id`='".$associationId."',`pers`='".$pers."',
				`modif`=NOW() where `id`=".$id;
        }else{
        	//insert
        	$sql = "insert into `".tblPrefix."persons` (`user_id`,`firstname`,`lastname`,`address`,`pers`,
										`zip`,`city`,`tel`,`emailp`,`association_id`,`created_on`,`modif`)
								 values (".$userId.",'".$firstName."','".$lastName."','".$address."','".$pers."',
								 		'".$zip."','".$city."','".$tel."','".$email."','".$associationId."',NOW(),NOW())";
        }		
		MAIN::executeCommand($sql);
		if($id==0){
			$personId=mysql_insert_id();
			$desc="New PERSON";
		}else{
			$personId = $id;
			$desc="PERSON Update";
		}
		LOGS::setLog('PROFILE', $desc, $personId, MAIN::getIP());    	
		return $personId;
    }	
	/** Function returning all persons in database table persons
	 * @param : order by, order order
	 * @return: array (Users)
	 */
    function getPersons($orderBy='lastname',$ord='asc'){    	
    	$tmpUser = USERS::getUser(-1);
    	$extra="";
    	/*if($tmpUser['association_id']!=""){
    		$extra ="OR `".tblPrefix."persons`.`association_id`=".$tmpUser['association_id'];
    	}*/
		$sql = "select `".tblPrefix."persons`.*,`".tblPrefix."users`.*,`".tblPrefix."users`.`active`,`".tblPrefix."persons`.`id`,`".tblPrefix."persons`.`association_id`, 
			(SELECT MAX(`".tblPrefix."logs`.`modif`) FROM `".tblPrefix."logs`								 
				WHERE `".tblPrefix."users`.`id` = `".tblPrefix."logs`.`user_id` 
				AND `".tblPrefix."logs`.`type` = 'LOGIN' 
				AND `".tblPrefix."logs`.`description` = 'success') as last_login 
		from `".tblPrefix."persons`			
		LEFT JOIN `".tblPrefix."users` ON (`".tblPrefix."persons`.`user_id`=`".tblPrefix."users`.`id` AND `".tblPrefix."users`.`grouplevel`>=".$tmpUser['grouplevel'].")
		order by `".$orderBy."` ".$ord;		
		if($tmpUser['grouplevel']==50){
			$associations = ASSOCIATIONS::getAssociations();
			$res = array();
			foreach($associations as $ass){
				$persons = ASSOCIATIONS::getAssociationMembers($ass['id']);
				foreach($persons as $pers){
					array_push($res, $pers);
				}				
			}
			return $res;
		}
		if($tmpUser['grouplevel']>50){
			return ASSOCIATIONS::getAssociationMembers($tmpUser['association_id']);
		}else{
			return MAIN::returnArray($sql);
		}		
	}
	/** Function returning all persons in database table persons
	 * @param : order by, order order
	 * @return: array (Users)
	 */
    function searchPersons($s,$orderBy='firstname',$ord='asc'){
    	$s = mysql_real_escape_string($s);
    	$tmpUser = USERS::getUser(-1);
    	$extra="";
    	/*if($tmpUser['association_id']!=""){
    		$extra ="OR `".tblPrefix."persons`.`association_id`=".$tmpUser['association_id'];
    	}*/
		$sql = "select `".tblPrefix."persons`.*,`".tblPrefix."users`.*,`".tblPrefix."users`.`active`,`".tblPrefix."persons`.`id`,`".tblPrefix."persons`.`association_id`, 
			(SELECT MAX(`".tblPrefix."logs`.`modif`) FROM `".tblPrefix."logs`								 
				WHERE `".tblPrefix."users`.`id` = `".tblPrefix."logs`.`user_id` 
				AND `".tblPrefix."logs`.`type` = 'LOGIN' 
				AND `".tblPrefix."logs`.`description` = 'success') as last_login 
		from `".tblPrefix."persons`			
		LEFT JOIN `".tblPrefix."users` ON (`".tblPrefix."persons`.`user_id`=`".tblPrefix."users`.`id` AND `".tblPrefix."users`.`grouplevel`>=".$tmpUser['grouplevel'].")
		WHERE (`".tblPrefix."persons`.`firstname` LIKE '%".$s."%' OR `".tblPrefix."persons`.`lastname` LIKE '%".$s."%')
		order by `".$orderBy."` ".$ord;
		if($tmpUser['grouplevel']==50){
			$associations = ASSOCIATIONS::getAssociations();
			$res = array();
			foreach($associations as $ass){
				$persons = ASSOCIATIONS::getAssociationMembers($ass['id']);
				foreach($persons as $pers){
					array_push($res, $pers);
				}				
			}
			return $res;
		}
		if($tmpUser['grouplevel']>50){
			$sql="select `".tblPrefix."persons`.*,`".tblPrefix."users`.`active`,`".tblPrefix."users`.`email`,(SELECT MAX(`".tblPrefix."logs`.`modif`) FROM `".tblPrefix."logs`								 
							WHERE `".tblPrefix."users`.`id` = `".tblPrefix."logs`.`user_id` 
							AND `".tblPrefix."logs`.`type` = 'LOGIN' 
							AND `".tblPrefix."logs`.`description` = 'success') as last_login  
			from `".tblPrefix."persons`
			LEFT JOIN `".tblPrefix."users` ON `".tblPrefix."persons`.`user_id`=`".tblPrefix."users`.`id`
			where `".tblPrefix."persons`.`association_id`=".$tmpUser['association_id']."
			AND (`".tblPrefix."persons`.`firstname` LIKE '%".$s."%' OR `".tblPrefix."persons`.`lastname` LIKE '%".$s."%')
			ORDER BY `".$orderBy."` ".$ord;
		}else{
			return MAIN::returnArray($sql);
		}
	}
	/** Function setting person user account
	 * @param : peronId, userId
	 * @return: boolean
	 */
	function setPersonUser($personId,$userId){
		$userId=mysql_real_escape_string($userId);
		$personId=mysql_real_escape_string($personId);
		$sql="update `".tblPrefix."persons` set `".tblPrefix."persons`.`user_id`=".$userId." where `".tblPrefix."persons`.`id`=".$personId;
		return MAIN::executeCommand($sql);
	}
	/**
	 * Function for removing user data from database
	 * @param : userId
	 * @return: void
	 */
    function delPerson($personId){    	
    	$sql="delete from `".tblPrefix."persons` where `id`=".$personId;
    	LOGS::setLog('PROFILE', "Person Delete", $personId, MAIN::getIP());
    	return MAIN::executeCommand($sql);
        
    }
	/** Function for checking User rights for level
	 * params: level
	 * return: boolean
	 */
    function checkUserPrivelige($level){
        $sql = "select id from users where grouplevel <= ".$level." AND id=".MAIN::decode($_SESSION['ts_user']);
        $res = MAIN::returnArray($sql);
        return (count($res)==0)?false:true;
    }
	/** Function for activating User 
	 * params: user ID
	 * return: void
	 */
    function activateUser($personId){
        $sql="update `users` set `active`=1 where `id`=".$personId;
        LOGS::setLog('ACTIVATE', "User activated", $personId, MAIN::getIP());
        return MAIN::executeCommand($sql);
    }
	/** Function for login in a user with or without cookie sessions
	 * params:
	 * return: boolean
	 */
    function doLogin($email, $password, $rememberMe=0){    	
		if(!empty($email) && !empty($password)){			
			//Check if there is a user in database with those username and password
			$sql = sprintf("select * from `".tblPrefix."users` where `email`='%s' and `active`=1",
						    mysql_escape_string($email)
						  );
			$req = mysql_query($sql)or die("error doLogin : ".mysql_error()."  sql : ".$sql);
            //Check if there has been some reposnse
			if(mysql_num_rows($req)>0){
				//There is user in database
				$row = mysql_fetch_assoc($req);
                $pass = MAIN::decode($row['drowp']); 
                if($pass!=$password){
                    LOGS::setLog('LOGIN', "failed", "wrong password: ".$email.' ('.$password.')', MAIN::getIP());
                    return false;
                }else{
				    //Set session
				    $_SESSION[svar] = MAIN::encode($row['id']);
				    //Set cookie
				    if($rememberMe==1){
					    @setcookie(svar, MAIN::encode($row['id']), time()+3600*24*10);
				    }else{
					    @setcookie (svar, "", time() - 3600);
				    }
                }
                LOGS::setLog('LOGIN', "success", MAIN::decode($_SESSION[svar]), MAIN::getIP());                
				return true;
			}else{
                LOGS::setLog('LOGIN', 'failed', 'missing email or not activated '.$email.' ('.$password.')', MAIN::getIP());
                return false;
            }
		}
	}
	/** Function for checking if a user is logged in or not
	 * param: redirect(bool) -> redirecting to start page
	 * return: boolean
	 */
    function checkLogin($redirect=true){
		if(@$_SESSION[svar]==''){
			if(@$_COOKIE[svar]==''){
				if($redirect){
					echo("<script>document.location.href='index.php?cat=login_full';</script>");
					exit();
				}else{
					return false;
				}
			}else{
                $_SESSION[svar] = $_COOKIE[svar];
                /* get user */
				$sql = "select * from `".tblPrefix."users` where `id`=".MAIN::decode($_COOKIE[svar]);					
				$req = mysql_query($sql)or die("error doLogin : ".mysql_error()."  sql : ".$sql);
				$row = mysql_fetch_assoc($req);
				return true;
			}
		}else{
			/* get user */
			$sql = "select * from `".tblPrefix."users` where `id`=".MAIN::decode($_SESSION[svar]);					
			$req = mysql_query($sql)or die("error doLogin : ".mysql_error()."  sql : ".$sql);
			$row = mysql_fetch_assoc($req);
			return true;
		}
	}
	/** Function for logging out from the system
	 * return : void
	 */
	function logout(){
		//log the event
	    LOGS::setLog('LOGOUT', 'user', MAIN::decode($_SESSION[svar]), MAIN::getIP());
	    //clean cookie
	    setcookie(svar, "", time()-1);
	    //clear session	    
	    unset($_SESSION[svar]);		
	    ?>
	    <script type="text/javascript">
		    document.location.href='index.php';
	    </script>
	    <?php
	}
	/**
	 * Function for generating a token for activation code (by email)
	 * params: userId
	 * return: string
	 */
    function generateActivationLink($personId){    	
		$token = MAIN::encode($personId);
		$link = "http://".$_SERVER['HTTP_HOST']."/register.php?token=".$token;		
		return $link;
	}
	/** Function for activating a user fromm the activation link
	 * params: token
	 * return: boolean || userId
	 */
    function activateUserFromLink($token){
		//This token contains userId i userEmail
		$personId = MAIN::decode($token);
		//$token = array ('id' => 'some_id', 'email' => 'some_email');
		$sql = sprintf("select * from `users` where `id`='%s' and `active`=0",
						    mysql_escape_string($personId)
						  );
		$req = mysql_query($sql)or die("error activateUserFromLink : ".mysql_error()."  sql : ".$sql);		
		//Check if there has been some reposnse
		if(mysql_num_rows($req)>0){
			$sql = sprintf("update `users` set `active`='1' where `id`='%s'",
						    mysql_escape_string($personId)
						  );
			$req = mysql_query($sql)or die("error activateUserFromLink : ".mysql_error()."  sql : ".$sql);
			return $personId;
		}else return false;
		return false;
	}
	/** Function for returning the UserLevel of the logged in user
	 * return: string (grouplevel)
	 */
    function getUserLevel(){
    	if(USERS::checkLogin(false)){
	    	$sql="select `grouplevel` from `users` where `id`=".MAIN::decode($_SESSION['ts_user']);
	    	$res = MAIN::returnArray($sql);
	    	return $res[0]['grouplevel'];
    	}else{    		
    		return 100;
    	}    	
	}
	/** Function for setting the UserLevel
	 * params: userId, Level
	 * return: void
	 */
	function setUserLevel($personId,$level){
    	$sql="update `users` set `grouplevel`='".$level."' WHERE `id`=".$personId;
    	MAIN::executeCommand($sql);   	    	
    	LOGS::setLog('GROUPLEVEL', "User GroupLevel updated to ".$level, $personId, MAIN::getIP());
	}
	/** Function for toggle activation on user
	 * params: userId
	 * return: void
	 */
	function toggleActivate($personId){
    	$sql="update `users` set `active`=ABS(active-1) where `id`=".$personId;
    	LOGS::setLog('ACTIVATE', "User activation updated", $personId, MAIN::getIP());
    	MAIN::executeCommand($sql);
    }
    /** Function for retrieving all groups
     * return : array
     */
	function getGroups(){
		$sql="select * from `groups`";
		$res = MAIN::returnArray($sql);
		return $res;
	}
	
	function setUserCompany($personId, $companyId){
		$sql ="update `users` set `company_id`=".$companyId." where `users`.`id`=".$personId;
		MAIN::executeCommand($sql);
	}
	function sendInvites($DATA){
		//print_r($DATA);
		$tempUser = USERS::getUser(-1);
		$tot = (count($DATA)-1)/2;
		for($i=1;$i<=$tot;$i++){
			if(isset($DATA['txt_email'.$i]) && $DATA['txt_email'.$i]!=""){
				$email = $DATA['txt_email'.$i];
				$subject = $tempUser['firstname']." ".$tempUser['lastname']." har inbjudit dig till Trafiksaker.se";
				$name = $DATA['txt_name'.$i];
				$message = mysql_real_escape_string(nl2br($DATA['txt_message']));
				$message = "Hej ".$name.",<br/>
				En av dina kollegor vill bjuda dig till att börja använda trafiksaker.se.<br/>
				Detta e-postmeddelande innehåller en länk som kommer att ge dig möjlighet att registrera dig och börja arbeta tilsammans med dina kollegor som finns redan registreade för trafiksaker.se<br/><br/>
				Personligt meddelande:<br/>
				<i>".$message."</i><br/><br/>
				Klicka på följande länk för att registrera dig.<br/>
				<a href=\"http://".$_SERVER['HTTP_HOST']."/?cat=register\">http://".$_SERVER['HTTP_HOST']."/?cat=register</a> 
				";
				if(!isset($TS)){
					$TS=new TS();
				}
				if($TS->sendMail($email, $subject, $message, true)){
					$sql="update `users` set `invites`=`invites`-1 where `id`=".$tempUser['id'];
					$TS->executeCommand($sql);
					return true;
				}else{
					return false;
				}
			}
		}
	}
}
?>